<template>
    <div>
      <el-upload class="avatar-uploader" action="fakeaction" :show-file-list="false" :http-request="uploadSectionFile">
         <div v-if="imageUrl" class="avatar_list">
           <img :src="imageUrl" class="avatar">
           <div class="icon_list">
             <i class="el-icon-zoom-in" @click.stop="handlePictureCardPreview"></i>
             <i class="el-icon-delete" @click.stop="handleRemove"></i>
           </div>
         </div>
         <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <!-- 图片预览 -->
      <el-dialog title="图片预览" :visible.sync="image_dialog_visible" width="60%">
        <img :src="imageUrl" class="image_dialog">
      </el-dialog>
    </div>
</template>
<script>
export default {
  name: 'sFileImage',
  data () {
    return {
      image_dialog_visible: false, // 预览
      imageUrl: '' // 图片路径
    }
  },
  props: {
    // 图片路径
    url: {
      type: String,
      default: ''
    }
  },
  watch: {
    url: function (val) { // 监听props中的属性
      this.imageUrl = val
    }
  },
  created () {
    this.imageUrl = this.url
  },
  methods: {
    handlePictureCardPreview () {
      this.image_dialog_visible = true
    },
    handleRemove () {
      this.imageUrl = ''
      this.$emit('confirm_imsge', { image_id: '', url: '' })
    },
    uploadSectionFile (params) {
      const file = params.file
      const fileType = file.type
      const isImage = fileType.indexOf('image') !== -1
      const isLt2M = file.size / 1024 / 1024 < 2
      // 这里常规检验，看项目需求而定
      if (!isImage) {
        return this.$base.message({ type: 'error', that: this, message: '只能上传图片格式png、jpg、gif！' })
      }
      if (!isLt2M) {
        return this.$base.message({ type: 'error', that: this, message: '只能上传图片大小小于2M！' })
      }
      const data = new FormData()
      data.append('file', file)
      this.$base.request({
        that: this,
        method: 'POST',
        url: 'auth/upload/file_image',
        data: data
      }, (res) => {
        if (res.code === 8888) {
          this.imageUrl = res.data.url
          this.$emit('confirm_imsge', { image_id: res.data.image_id ? res.data.image_id : '', url: res.data.url })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.image_dialog{
  width: 100%;
}
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px;
  }
  .avatar-uploader-icon:hover {
    border-color: #409EFF;
  }
  .avatar_list{
    width: 178px;
    position: relative;
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .icon_list{
      position: absolute;
      top:0;
      width: 178px;
      height: 178px;
      display: block;
      i{
        width: 28px;
        height: 28px;
        margin: 20px;
        font-size: 28px;
        color: #FFFDEF;
      }
    }
  }

</style>
